import { NextRequest, NextResponse } from 'next/server'
import { writeFile } from 'fs/promises'
import path from 'path'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

//疑似为上传文件创建阶段准备
export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 })
  }

  try {
    const formData = await req.formData()
    const file = formData.get('file') as File | null
    const experimentId = formData.get('experimentId') as string | null
    const stageId = formData.get('stageId') as string | null

    if (!file) {
      return NextResponse.json({ error: 'No file provided.' }, { status: 400 })
    }
    
    if (!experimentId) {
      return NextResponse.json({ error: 'Experiment ID is required.' }, { status: 400 })
    }

    const experiment = await prisma.experiment.findUnique({
      where: { id: experimentId },
      select: { id: true }
    })
    if (!experiment) {
      return NextResponse.json({ error: 'Experiment not found.' }, { status: 404 })
    }

    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    const originalFilename = file.name
    const extension = path.extname(originalFilename)
    const baseFilename = path.basename(originalFilename, extension)
    
    let uniqueFilename
    let uploadSubDir
    let publicSubDir

    if (stageId) {
      uniqueFilename = `${session.user.id}_exp${experimentId}_stage${stageId}_${Date.now()}_${baseFilename.replace(/[^a-zA-Z0-9_\-\.]/g, '_')}${extension}`
      uploadSubDir = path.join(experimentId, 'stages', stageId)
      publicSubDir = `${experimentId}/stages/${stageId}`
    } else {
      uniqueFilename = `exp${experimentId}_resource_${Date.now()}_${baseFilename.replace(/[^a-zA-Z0-9_\-\.]/g, '_')}${extension}`
      uploadSubDir = path.join(experimentId, 'resources')
      publicSubDir = `${experimentId}/resources`
    }
    
    const uploadDirRoot = path.join(process.cwd(), 'public', 'uploads')
    const finalUploadDir = path.join(uploadDirRoot, uploadSubDir)
    const filePath = path.join(finalUploadDir, uniqueFilename)

    const fs = require('fs').promises
    await fs.mkdir(finalUploadDir, { recursive: true })

    await writeFile(filePath, buffer)
    console.log(`File uploaded to ${filePath}`)

    const publicUrl = `/uploads/${publicSubDir}/${uniqueFilename}`

    return NextResponse.json({
      success: true,
      message: 'File uploaded successfully',
      fileName: originalFilename,
      fileUrl: publicUrl,
    })

  } catch (error) {
    console.error('Error uploading file:', error)
    return NextResponse.json({ error: 'File upload failed.', details: (error as Error).message }, { status: 500 })
  }
} 